<template>
    <div class="user-login-container">
        <template v-if="type != 'register'">
            <!-- 密码登录 -->
            <template v-if="type == 'password-login'">
                <el-form
                    :ref="(e) => (loginByPassword.formRef = e)"
                    :rules="loginByPassword.rules"
                    :model="loginByPassword.data">
                    <el-form-item prop="username" style="margin-bottom: 24px">
                        <div class="field" style="widows: 40px">
                            <el-input
                                id="input"
                                size="large"
                                v-model="loginByPassword.data.username"
                                placeholder="请输入账号"
                                @keyup.enter="loginByPassword.login"></el-input>
                        </div>
                    </el-form-item>
                    <el-form-item prop="password" style="margin-bottom: 24px">
                        <div class="field">
                            <el-input
                                show-password
                                size="large"
                                v-model="loginByPassword.data.password"
                                type="password"
                                placeholder="请输入密码"
                                @keyup.enter="loginByPassword.login"></el-input>
                        </div>
                    </el-form-item>

                    <el-form-item prop="captcha" style="margin-bottom: 24px">
                        <div class="field">
                            <el-input
                                size="large"
                                v-model="loginByPassword.data.captcha"
                                placeholder="请输入验证码"
                                style="width: calc(100% / 3 * 2)"
                                @keyup.enter="loginByPassword.login"></el-input>
                            <img
                                :src="loginByPassword.vaildImgSrc"
                                @click="loginByPassword.getCaptcha"
                                style="width: calc(100% / 3 * 2); margin-left: 15px" />
                        </div>
                    </el-form-item>

                    <div class="field" style="margin-bottom: 26px">
                        <span class="checkbox-group" style="display: flex; align-items: center">
                            <el-checkbox
                                style="color: #606266"
                                v-model="loginByPassword.data.rememberMe"></el-checkbox>
                            <span
                                class="text"
                                @click="
                                    loginByPassword.data.rememberMe =
                                        !loginByPassword.data.rememberMe
                                "
                                >15天内记住密码</span
                            >
                        </span>
                    </div>
                    <div class="field login-botton">
                        <!--   style="
                                width: 100%;
                                height: 40px;
                                border-radius: 2px;
                                background: #3b78ff99;
                            " -->
                        <el-button
                            @click.prevent="loginByPassword.login"
                            size="large"
                            type="primary"
                            class="login-btn login-style"
                            >登录</el-button
                        >
                    </div>
                    <div
                        style="
                            font-size: 14px;
                            text-align: center;
                            padding-top: 20px;
                            color: #606266;
                        ">
                        若无账号，请联系本单位管理员进行分配
                    </div>
                </el-form>
                <div v-if="!hideRegister" class="field toRegister">
                    <div class="toRegister" style="font-size: 12px">
                        <div>还没有账号？</div>
                        <div style="margin-left: 4px">
                            <el-button @click="switchType('register')" size="large" link>
                                <div style="display: flex; align-items: center; font-size: 12px">
                                    <div>立即注册</div>
                                    <div>
                                        <img
                                            style="margin-left: 13px"
                                            src="@/assets/images/vector.svg" />
                                    </div>
                                </div>
                            </el-button>
                        </div>
                    </div>
                </div>
            </template>

            <!-- 验证码登录 -->
            <template v-if="type == 'vercode-login'">
                <el-form
                    :ref="(e) => (loginByVerCode.formRef = e)"
                    :rules="loginByVerCode.rules"
                    :model="loginByVerCode.data">
                    <el-form-item prop="MobilePhone" style="margin-bottom: 24px">
                        <div class="field">
                            <el-input
                                size="large"
                                v-model="loginByVerCode.data.MobilePhone"
                                placeholder="手机号"></el-input>
                        </div>
                    </el-form-item>
                    <el-form-item prop="Vercode" style="margin-bottom: 24px">
                        <div class="flex">
                            <el-input
                                size="large"
                                v-model="loginByVerCode.data.Vercode"
                                placeholder="验证码"
                                style="width: 177px; border: none"></el-input>
                            <el-button
                                @click="loginByVerCode.sendVerCode"
                                :disabled="loginByVerCode.disabledSendBtn"
                                class="send-vercode-btn"
                                type="primary"
                                size="large">
                                <template v-if="loginByVerCode.countTime <= 0">发送验证码</template>
                                <template v-else
                                    >重新发送 ({{ loginByVerCode.countTime }})</template
                                >
                            </el-button>
                        </div>
                    </el-form-item>

                    <div class="field" style="margin-bottom: 35px">
                        <span class="checkbox-group">
                            <el-checkbox v-model="loginByVerCode.data.rememberMe"></el-checkbox>
                            <span
                                class="text"
                                @click="
                                    loginByVerCode.data.rememberMe = !loginByVerCode.data.rememberMe
                                "
                                >15天记住密码</span
                            >
                        </span>
                    </div>
                    <div class="field login-botton">
                        <el-button
                            @click="loginByVerCode.login"
                            size="large"
                            type="primary"
                            class="login-btn login-style"
                            >登录</el-button
                        >
                    </div>
                </el-form>
                <div v-if="!hideRegister" class="field toRegister">
                    <div class="toRegister" style="font-size: 12px">
                        <div>还没有账号？</div>
                        <div style="margin-left: 4px">
                            <el-button @click="switchType('register')" size="large" link>
                                <div style="display: flex; align-items: center; font-size: 12px">
                                    <div>立即注册</div>
                                    <div>
                                        <img
                                            style="margin-left: 13px"
                                            src="@/assets/images/vector.svg" />
                                    </div>
                                </div>
                            </el-button>
                        </div>
                    </div>
                </div>
            </template>

            <!-- 微信登录 -->
            <template v-if="type == 'wechat-login'">
                <div class="wechat-title">
                    <div>
                        <img src="@/assets/images/login-wechat.svg" />
                    </div>
                    <div class="wechat-text">微信扫码登录</div>
                </div>
                <div id="wx-login-container"></div>
            </template>

            <div class="switcher">
                <div class="switcher-type" v-if="type != 'password-login'">
                    <el-button @click="switchType('password-login')" size="large" link>
                        <div class="login-type">
                            <div class="img">
                                <img src="@/assets/images/login-password.svg" />
                            </div>
                            <div>密码登录</div>
                        </div>
                    </el-button>
                </div>
                <div class="switcher-type" v-if="type != 'vercode-login'">
                    <el-button @click="switchType('vercode-login')" size="large" link>
                        <div class="login-type">
                            <div class="img">
                                <img src="@/assets/images/login-vercode.svg" />
                            </div>
                            <div>验证码登录</div>
                        </div>
                    </el-button>
                </div>

                <div class="switcher-type" v-if="type != 'wechat-login'">
                    <el-button @click="switchType('wechat-login')" size="large" link>
                        <div class="login-type">
                            <div class="img">
                                <img src="@/assets/images/login-wechat.svg" />
                            </div>
                            <div>微信登录</div>
                        </div>
                    </el-button>
                </div>
                <!-- <div v-if="type != 'wechat-login'">
                    <el-button @click="switchType('wechat-login')" size="large" link>微信登录</el-button>
                </div>-->
            </div>
        </template>
        <template v-else>
            <el-form
                :ref="(e) => (register.formRef = e)"
                :rules="register.rules"
                :model="register.data">
                <el-form-item prop="mobilePhone" style="margin-bottom: 24px">
                    <div class="field">
                        <el-input
                            size="large"
                            v-model="register.data.mobilePhone"
                            placeholder="请输入11位手机号"></el-input>
                    </div>
                </el-form-item>

                <el-form-item prop="verCode" style="margin-bottom: 28px">
                    <div class="field">
                        <el-input
                            v-model="register.data.verCode"
                            size="large"
                            placeholder="请输入验证码"></el-input>
                        <el-button
                            @click="register.sendVerCode"
                            :disabled="register.disabledSendVerCode"
                            class="send-vercode-btn"
                            type="primary"
                            >发送验证码</el-button
                        >
                    </div>
                </el-form-item>

                <!-- <el-form-item prop="verCode" style="margin-bottom:64px">
                    <el-checkbox size="large" v-model="register.data.read">
                        注册即表示您已阅读、理解并同意
                        <el-button link>《及时通隐私政策》</el-button>
                    </el-checkbox>
                </el-form-item>-->

                <el-button
                    class="main-btn"
                    @click="register.submit"
                    :disabled="register.submitButtonLock"
                    type="primary"
                    >注 册</el-button
                >
                <div class="field toRegister">
                    <div class="toRegister">
                        <div>已有账号？</div>
                        <div style="margin-left: 4px">
                            <el-button
                                @click="switchType('password-login')"
                                size="large"
                                link
                                style="font-size: 12px">
                                <div style="display: flex; align-items: center; font-size: 12px">
                                    <div>直接登录</div>
                                    <div>
                                        <img
                                            style="margin-left: 13px"
                                            src="@/assets/images/vector.svg" />
                                    </div>
                                </div>
                            </el-button>
                        </div>
                    </div>
                </div>
            </el-form>
        </template>
    </div>
</template>

<script>
// 用户登录框 (包含注册)
import { computed, defineComponent, reactive, ref, nextTick, onMounted } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import { useUserRegisterMobilePhone } from '@/composables/userRegister'
import { useRouter } from 'vue-router'
import { utils } from 'justom-share'
import request from '@/public/request'
import { useStore } from 'vuex'
import WxLogin from '@/public/wxLogin'
import { encrypt, decrypt } from '@/utils/rsaEncrypt'
import Cookies from 'js-cookie'
function registerRef() {
    const router = useRouter()
    function submitSuccess(token) {
        router.push({
            path: '/register',
            query: {
                token: encodeURI(token),
            },
        })
    }

    const registerRef = useUserRegisterMobilePhone(submitSuccess)

    return reactive(registerRef)
}

function loginByPasswordRef(store, success) {
    const formRef = ref(null)
    const router = useRouter()
    const data = ref({
        username: '',
        password: '',
        captcha: '',
        captchaId: '',
        rememberMe: false,
    })
    const vaildImgSrc = ref('')
    const rules = reactive({
        username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        captcha: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
    })
    /**
     * 获取验证码
     */
    function getCaptcha() {
        request.get('/auth/captcha').then((res) => {
            data.value.captchaId = res.captchaId
            vaildImgSrc.value = res.img
        })
    }
    /**
     * 登录
     */
    async function login() {
        await formRef.value.validate()
        const loading = ElLoading.service({
            lock: true,
        })
        // 用cookies记住当前的密码
        if (!data.value.rememberMe) {
            Cookies.remove('userName')
            Cookies.remove('passWord')
        } else {
            let { userName, passWord } = Cookies.get()
            if (!userName) {
                Cookies.set('userName', data.value.username, { expires: 15 })
                Cookies.set('passWord', encrypt(data.value.password), { expires: 15 })
            }
        }
        try {
            let res = await request.post('/auth/login', {
                username: data.value.username,
                password: encrypt(data.value.password),
                captcha: data.value.captcha,
                captchaId: data.value.captchaId,
            })
            if (res.status) {
                await store.dispatch('auth/setTokenAndGetInfo', res.data.token).catch(() => {})
                await store.dispatch('menu/getCurrentEmployeeMenuTree')
                await store.dispatch('tab/initTabOnlyHome')
                localStorage.setItem('userName', res.data.user.user.username)
                if (success) {
                    success()
                }
            } else {
                ElMessage.error(res.message)
                data.value.password = ''
                data.value.captcha = ''
            }
            getCaptcha()
            loading.close()
            // let onlyHome=JSON.stringify([{title:"首页",route:"/internal/home"}])
            // localStorage.setItem('jst:tabs',onlyHome)
            // await store
            //   .dispatch("auth/setTokenAndGetInfo", res.token)
            //   .catch(() => {});
            // if (success) {
            //   success();
            // }
            // getCaptcha();
            // loading.close();
        } catch (err) {
            ElMessage.error(err)
            console.log(err)
            getCaptcha()
            loading.close()
            return
        }

        // let res = await request.post("/api/auth/login?username=" + data.value.username + '&password=' + data.value.password + '&captcha=' + '&captchaId=');
    }

    return reactive({
        formRef,
        data,
        rules,
        login,
        vaildImgSrc,
        getCaptcha,
    })
}

function loginByVerCodeRef(store, success) {
    const router = useRouter()
    const formRef = ref(null)
    const data = ref({
        MobilePhone: '',
        Vercode: '',
        Password: '',
        LoginByPassword: false,
        rememberMe: false,
    })
    // 是否禁用发送验证码
    const disabledSendBtn = ref(true)

    // 验证码冷却时间
    const countTime = ref(-1)

    const rules = reactive({
        MobilePhone: [
            {
                message: '请输入正确的手机号',
                validator: (rule, value, callback) => {
                    if (utils.checkMobilePhone(value)) {
                        callback()
                        if (disabledSendBtn.value == true && countTime.value < 0) {
                            disabledSendBtn.value = false
                        }
                    } else {
                        callback(new Error('请输入正确的手机号'))
                        disabledSendBtn.value = true
                    }
                },
                trigger: 'blur',
            },
        ],
        Vercode: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
    })

    // 获得token 前往注册
    function registerSuccessHandler(registerToken) {
        router.push({
            path: '/register',
            query: {
                token: encodeURI(registerToken),
            },
        })
    }

    // 注册相关
    const register = useUserRegisterMobilePhone(registerSuccessHandler)

    // 发送验证码
    async function sendVerCode() {
        if (utils.checkMobilePhone(data.value.MobilePhone) == false) {
            ElMessage.warning('请输入正确的手机号')
            return
        }

        disabledSendBtn.value = true

        // 检查手机号是否注册
        let isRegister = await request.get('/api/User/GetUserBaseInfoByMobilePhone', {
            mobilePhone: data.value.MobilePhone,
        })
        if (isRegister.Status == false) {
            // 未注册
            register.data.value.mobilePhone = data.value.MobilePhone
            if (await register.sendVerCode()) {
                countTime.value = 60
                let intervalId = setInterval(() => {
                    countTime.value -= 1
                    if (countTime.value <= 0) {
                        clearInterval(intervalId)
                        countTime.value = -1
                        // 一分钟后解锁
                        disabledSendBtn.value = false
                    }
                }, 1000)
            } else {
                // 出现错误 马上解锁
                disabledSendBtn.value = false
            }
        } else {
            // 已注册
            let res = await request.post('/api/UserVerCode/SendVerCode', {
                mobilePhone: data.value.MobilePhone,
                type: 0,
            })
            if (res.Status) {
                ElMessage.success('验证码发送成功')

                countTime.value = 60
                let intervalId = setInterval(() => {
                    countTime.value -= 1
                    if (countTime.value <= 0) {
                        clearInterval(intervalId)
                        countTime.value = -1
                        // 一分钟后解锁
                        disabledSendBtn.value = false
                    }
                }, 1000)
            } else {
                ElMessage.error(res.Message)
                // 出现错误 马上解锁
                disabledSendBtn.value = false
            }
        }
    }

    /**
     * 登录
     */
    async function login() {
        await formRef.value.validate()

        const loading = ElLoading.service({
            lock: true,
        })

        // 检查手机号是否注册
        let isRegister = await request.get('/api/User/GetUserBaseInfoByMobilePhone', {
            mobilePhone: data.value.MobilePhone,
        })
        if (isRegister.Status == false) {
            // 未注册

            register.data.value.verCode = data.value.Vercode
            register.data.value.mobilePhone = data.value.MobilePhone
            await register.submit(true).finally(() => {
                loading.close()
            })
        } else {
            // 已注册
            let res = await request.post('/api/AuthUser/Login', data.value)

            if (!res.Status) {
                ElMessage.error(res.Message)
                loading.close()
                return
            }
            await store.dispatch('auth/setTokenAndGetInfo', res.Data).catch(() => {})
            loading.close()
            if (success) {
                success()
            }
        }
    }

    return reactive({
        formRef,
        data,
        rules,
        login,
        sendVerCode,
        disabledSendBtn,
        countTime,
    })
}

export default defineComponent({
    props: {
        hideRegister: {
            type: Boolean,
            default: false,
        },
    },
    emits: ['success'],
    setup(props, context) {
        const store = useStore()

        /*
        password-login 密码登录
        vercode-login 验证码登录
        wechat-login 微信登录
        register 注册

        */

        const type = ref('password-login')
        const title = computed(() => {
            let text = ''
            switch (type.value) {
                case 'password-login':
                    text = '密码登录'
                    break
                case 'vercode-login':
                    text = '验证码登录'
                    break
                case 'wechat-login':
                    text = ''
                    break
                case 'register':
                    text = '手机注册'
                    break
                default:
                    break
            }

            return text
        })

        function success() {
            // 登录成功后触发
            context.emit('success')
        }

        const register = registerRef()
        const loginByPassword = loginByPasswordRef(store, success)
        const loginByVerCode = loginByVerCodeRef(store, success)

        function switchType(target) {
            type.value = target

            if (target === 'wechat-login') {
                nextTick(async () => {
                    let style = `
                    .loginPanel .title{
                        display:none;
                    }
                    .info{
                        display:none;
                    }
                    .qrcode{
                        width:148px !important;
                        height:148px !important;
                    }
                    `

                    let res = await request.get('/api/Wechat/GetWechatConfig')
                    /*
                    data:text/css;base64,LmltcG93ZXJCb3ggLnFyY29kZSB7d2lkdGg6IDIwMHB4O30NCi5pbXBvd2VyQm94IC50aXRsZSB7ZGlzcGxheTogbm9uZTt9DQouaW1wb3dlckJveCAuaW5mbyB7d2lkdGg6IDIwMHB4O30NCi5zdGF0dXNfaWNvbiB7ZGlzcGxheTpub25lf
                    Q0KLmltcG93ZXJCb3ggLnN0YXR1cyB7dGV4dC1hbGlnbjogY2VudGVyO30=
                    */

                    // 微信登录
                    WxLogin({
                        self_redirect: false,
                        id: 'wx-login-container',
                        appid: res.AppId,
                        scope: 'snsapi_login',
                        redirect_uri: res.Host + '/api/AuthUser/WxLoginOrRegister',
                        state: '',
                        style: '',
                        href: 'data:text/css;base64,' + window.btoa(style),
                    })
                })
            }
        }

        onMounted(() => {
            loginByPassword.getCaptcha()
            //是否已经保存之前登录时的密码
            let { userName, passWord } = Cookies.get()
            if (userName) {
                loginByPassword.data.username = userName
                loginByPassword.data.rememberMe = true
            }
            if (passWord) {
                loginByPassword.data.password = decrypt(passWord)
            }
            // store.dispatch("auth/logout");
        })

        return {
            type,
            title,
            register,
            loginByPassword,
            loginByVerCode,
            switchType,
        }
    },
})
</script>

<style lang="scss">
.user-login-container {
    .el-dialog__header {
        padding-top: 24px;
        font-size: 20px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #3c4144;
        line-height: 28px;
        padding-left: 32px;
        padding-right: 32px;
    }

    .field {
        width: 100%;
    }

    .el-dialog__body {
        padding-top: 14px;
        padding-left: 32px;
        padding-right: 32px;
        padding-bottom: 32px;
    }

    .el-input__wrapper {
        height: 40px;
        background-color: #f5f7fa;
        box-shadow: none;
        border-radius: 2px;
        border: 1px solid #d9dbdf;
    }
}
</style>
<style lang="scss" scoped>
.field {
    display: flex;
    justify-content: space-between;
    // width: 320px;
}

.flex {
    display: flex;
}

.toRegister {
    display: flex;
    justify-content: space-between;
    margin: 0 auto;
    line-height: 48px;
    font-size: 12px;
}

.toLogin {
    display: flex;
    justify-content: space-between;
    margin: 0 auto;
    line-height: 40px;
}

.switcher {
    margin-top: 33px;
    // display: flex;
    justify-content: space-around;
    margin: 0 auto;
    width: 140px;
    height: 30px;
    display: none;
}

.login-type {
    height: 16px;
    line-height: 18px;
    display: flex;
    color: #909399;

    &:hover {
        color: #409eff;
    }

    .img {
        margin-right: 8px;
    }
}

.main-btn {
    width: 100%;
    height: 50px;
    font-size: 16px;
    border-radius: 4px;
}

.send-vercode-btn {
    width: 165px;
    margin-left: 8px;
    border-radius: 4px;
    border-radius: 4px;
    font-size: 16px;
    height: 50px;
}

.login-btn {
    font-size: 16px;
}

.login-style {
    width: 100%;
    height: 40px;
    border-radius: 2px;
    background: #3b78ff99;
    border-radius: 4px;
    font-size: 16px;
}

.checkbox-group {
    .text {
        cursor: pointer;
        margin-left: 4px;
    }
}

.switcher-type:first-child {
    margin-right: 34px;
}

#wx-login-container {
    height: 197px;
    text-align: center;
    overflow: hidden;
    margin-top: 33px;
}

.wechat-title {
    display: flex;
    justify-content: center;
    position: absolute;
    top: 24px;
    left: 131px;

    img {
        $size: 24px;
        width: $size;
        height: $size;
        margin-top: 2px;
    }

    .wechat-text {
        font-size: 20px;
        color: #3c4144;
        margin-left: 8px;
    }
}

.login-botton {
    :deep(.el-button) {
        border-color: transparent;
    }
}
</style>
